package com.xx.web.websocket.client;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.ContainerProvider;
import javax.websocket.Session;
import javax.websocket.WebSocketContainer;
import java.net.URI;

/**
 * @author ghh
 * @date 2019-08-16 16:02
 */
@Component
@Slf4j
public class WSClient {
    public static Session session;

    public static void startWS() {
        Thread thread = new Thread(() -> {
            try {
                if (WSClient.session != null) {
                    WSClient.session.close();
                }
                WebSocketContainer container = ContainerProvider.getWebSocketContainer();
                //设置消息大小最大为10M
                container.setDefaultMaxBinaryMessageBufferSize(10 * 1024 * 1024);
                container.setDefaultMaxTextMessageBufferSize(10 * 1024 * 1024);
                // 客户端，开启服务端websocket。
                //String uri = "ws://localhost:9120/wb/track/admin_9125";
                String uri = "ws://115.231.209.18:8088/wb/track/16899248186";
                Session session = container.connectToServer(MyWebSocketClient.class, URI.create(uri));
                WSClient.session = session;

            } catch (Exception ex) {
                log.info(ex.getMessage());
                try {
                    Thread.sleep(3000);
                    startWS();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        thread.setDaemon(true);
        thread.start();
    }
}
